package org.aurora.common.delay.queue;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Author wangxuehao02
 * @Description
 *
 * 延迟执行任务，到期执行从队列弹出后执行回调
 **/

public class DelayExecuteTaskQueue<E extends DelayTask> extends DelayQueue<E> {
    private static final Logger log = LoggerFactory.getLogger(DelayExecuteTaskQueue.class);

    private Thread executeThread;

    private DelayExecuteTaskActuator delayExecuteTaskActuator;

    private String executeThreadName;

    private final AtomicBoolean isStart = new AtomicBoolean(false);
    private volatile boolean isStop = false;

    public DelayExecuteTaskQueue(String executeThreadName, DelayExecuteTaskActuator<E> delayExecuteTaskActuator) {
        this.executeThreadName = executeThreadName;
        this.delayExecuteTaskActuator = delayExecuteTaskActuator;
    }

    public void start() {
        if (isStart.compareAndSet(false, true)) {
            executeThread = new Thread(() -> {
                while (!isStop) {
                    try {
                        DelayTask delayTask = this.take();

                        delayExecuteTaskActuator.execute(delayTask);
                    } catch (Exception e) {
                        log.error("DelayExecuteTaskQueue {} execute error = {}", executeThreadName, e);
                    }
                }
            }, executeThreadName);

            executeThread.start();
        }
    }

    public void stop() {
        isStop = true;
    }

    public interface DelayExecuteTaskActuator<E extends DelayTask> {
        void execute(E delayTask);
    }
}
